﻿using Cognex.VisionPro;
using Cognex.VisionPro.Display;
using Cognex.VisionPro.ImageFile;
using Cognex.VisionPro.ToolBlock;
using log4net;
using log4net.Appender;
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls.WebParts;
using System.Windows.Forms;
using WindowsFormsApp2.Common;
using WindowsFormsApp2.Froms;
using WindowsFormsApp2.JiayuModelset;
using YJYpublicClass;

namespace WindowsFormsApp2
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;   //允许跨线程访问不报错，参数加载完后关闭
        }

        Frm_Welcome welcomefrom = new Frm_Welcome();

        Frm_DispImg frmDisp_TopCamera1 = new Frm_DispImg();
        Frm_DispImg frmDisp_TopCamera2 = new Frm_DispImg();
        Frm_DispImg frmDisp_LowCamera1 = new Frm_DispImg();
        Frm_DispImg frmDisp_LowCamera2 = new Frm_DispImg();

        Boolean InitOK = false; //初始化状态标志
        int ExitSta = 0;  //程序退出标志

        //再定义取图工具
        //app状态
        int Appstates = 0;
        //0，手动，1自动运行，2异常


        private void MainForm_Load(object sender, EventArgs e)
        {
            //先把屏幕关掉
            this.Visible = false;
            this.Opacity = 0;
            Task t1 = new Task(AppINIT);
            t1.Start();
            welcomefrom.ShowDialog();
            welcomefrom.Dispose();
            //初始化之后调整窗口，启动线程
            窗口调整();
            this.WindowState = FormWindowState.Maximized;
            //启动图像处理线程，处理图像
            //启动主线程
            ExitSta = 1;
            main_thread.RunWorkerAsync();
            //DoOtherWork.RunWorkerAsync();
            topWorker.RunWorkerAsync();
            lowWorker.RunWorkerAsync();
            显示_tick.Enabled = true;
            cbx_图像保存.Checked = 外设.SysPras.SaveImageFlag;

            if (InitOK)
            {
                myLog4.Info("软件初始化完成!");
                //触发一次自动设置
            }
            else
            {
                myLog4.Info("程序初始化失败,请检查相关配置");
            }
            this.Visible = true;
            this.Opacity = 1;


            //显示
            this.Invoke((EventHandler)delegate
            {
                FormDockToPanel(frmDisp_TopCamera1, this.splitContainer2.Panel1);
                frmDisp_TopCamera1.lab_station.Text = "上-1";
                FormDockToPanel(frmDisp_TopCamera2, this.splitContainer2.Panel2);
                frmDisp_TopCamera2.lab_station.Text = "上-2";
                FormDockToPanel(frmDisp_LowCamera1, this.splitContainer3.Panel1);
                frmDisp_LowCamera1.lab_station.Text = "下-1";
                FormDockToPanel(frmDisp_LowCamera2, this.splitContainer3.Panel2);
                frmDisp_LowCamera2.lab_station.Text = "下-2";
            });

        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {

            DialogResult dr = MessageBox.Show("\r确定退出软件吗?", "系统提示", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                ExitSta = 0;
                Thread.Sleep(500);
                外设.LightCtrl.CloseAll();
                外设.LightCtrl.Close();
                外设.rtuClient.Close();
                //直接结束线程
                PublicFuntions.KillProcess("WindowsFormsApp2");    //强制结束进程              
            }
            else
            {
                e.Cancel = true;
            }
        }

        #region=================================初始化函数======================================
        private void AppINIT()
        {
            try
            {
                InitOK = true;
                welcomefrom.LoadingProgress(10, "系统初始化", 500);
                if (!InitSystem())
                {
                    InitOK = false;
                }
                welcomefrom.LoadingProgress(20, "读取参数", 500);
                //日志初始化,并绑定显示
                myLog4.LogInit(rtb_Log);
                if (!ReadParameters())
                {
                    InitOK = false;
                }
                myLog4.Info("参数加载完成");
                //运动控制卡初始化
                // Thread.Sleep(100);
                //图像处理初始化
                welcomefrom.LoadingProgress(30, "初始化PLC通讯", 500);
                
                if (!外设.rtuClient.Init())
                {
                    InitOK = false;
                    myLog4.Info("PLC初始化失败");
                }
                外设.rtuClient.WriteShort(外设.rtuClient.rtuConfig.PhotoCam.ToString(), 0);
                //读取当前PLC款式信息  
                welcomefrom.LoadingProgress(40, "启动心跳软件", 500);
                if (!HeartInit())
                {
                    InitOK = false;
                    myLog4.Info("启动心跳软件失败");
                }
                myLog4.Info("加载标定文件");
                //PLC初始化
                welcomefrom.LoadingProgress(60, "加载算法款式文件", 500);
                if (!kuanshiInit())
                {
                    InitOK = false;
                    myLog4.Info("款式自动加载失败，请手动加载");
                }

                welcomefrom.LoadingProgress(80, "光源初始化", 500);
                if (!LightInit())
                {
                    InitOK = false;
                    myLog4.Info("光源初始化失败");
                }
                //Thread.Sleep(100);
                welcomefrom.LoadingProgress(100, "加载完成", 200);
                welcomefrom.CloseForm = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }


        /// <summary>
        /// 初始化系统设置
        /// </summary>
        /// <returns></returns>
        private bool InitSystem()
        {
            try
            {
                string ProcessName = Process.GetCurrentProcess().ProcessName;
                Process[] cur = Process.GetProcessesByName(ProcessName);
                if (cur.Length > 1)
                {
                    ExitSta = 0;
                    MessageBox.Show("检测到进程中已有相同软件打开,请勿重复打开软件！");
                    Application.Exit();
                }
                // PublicValue.AppDirectory
                PublicValue.SystemIniPath = Application.StartupPath + @"\System.ini";
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private void 窗口调整()
        {
            try
            {
                //=============================================居中显示主界面================================================
                Rectangle Rect = new Rectangle();
                Rect = Screen.GetWorkingArea(this);    //显示器分辨率
                int FormHeight = this.Height;          //窗体大小
                int FormWidth = this.Width;
                this.Location = new System.Drawing.Point((Rect.Width - FormWidth) / 2, (Rect.Height - FormHeight) / 2);
                //=============================================绑定图像窗口==================================================
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 读取参数,只读取全局变量参数
        /// </summary>
        /// <returns></returns>
        /// 
        //读参数，读取当前
        public Boolean ReadParameters()
        {
            try
            {
                //=============================================读取系统配置参数===============================================
                if (File.Exists(SystemPras.SyspPrasFpath))
                {
                    外设.SysPras = XmlHelper.LoadXML<SystemPras>(SystemPras.SyspPrasFpath);
                    if (外设.SysPras == null)
                    {
                        外设.SysPras = new SystemPras();
                    }
                }
                else
                {
                    外设.SysPras = new SystemPras();
                }

                var rootAppender = ((Hierarchy)LogManager.GetRepository())
                             .Root.Appenders.OfType<FileAppender>()
                             .FirstOrDefault();

                string filename = rootAppender != null ? rootAppender.File : string.Empty;
                string direct = Path.GetDirectoryName(filename);
                外设.SysPras.Logpath = direct;
                //=======读取标定文件=============

                if (File.Exists(SystemPras.Calibfile))
                {
                    外设.Calibdatas = XmlHelper.LoadXML<CalibDataList>(SystemPras.Calibfile);
                    if (外设.Calibdatas == null)
                    {
                        外设.Calibdatas = new CalibDataList();
                    }
                }
                else
                {
                    外设.Calibdatas = new CalibDataList();
                }

                //====生产数据====//
                PublicValue.TopOk = int.Parse(PublicFuntions.GetINI("生产数据", "TopOk", "0", PublicValue.SystemIniPath));
                PublicValue.TopNg = int.Parse(PublicFuntions.GetINI("生产数据", "TopNg", "0", PublicValue.SystemIniPath));
                PublicValue.LowOk = int.Parse(PublicFuntions.GetINI("生产数据", "LowOk", "0", PublicValue.SystemIniPath));
                PublicValue.LowNg = int.Parse(PublicFuntions.GetINI("生产数据", "LowNg", "0", PublicValue.SystemIniPath));
                PublicValue.sleepTime = int.Parse(PublicFuntions.GetINI("生产数据", "SleepTime", "0", PublicValue.SystemIniPath));
                PublicValue._chanliangdata = DateTime.Parse(PublicFuntions.GetINI("生产数据", "datetime", DateTime.Now.ToString(), PublicValue.SystemIniPath));

                this.numUD_SleepTime.Text = PublicValue.sleepTime.ToString();

                return true;
            }
            catch (System.Exception ex)
            {
                myLog4.Info("参数读取失败！");
                return false;
            }
        }

        //private Boolean IPInit()
        //{
        //    try
        //    {
        //        if (外设.VPPmeth.intAllvpp() == "")
        //        {
        //            // 外设.VPPmeth.cogDisplaywindow = this.cogRecordDisplay1;
        //            return true;
        //        }
        //        else
        //        {
        //            RunLogMessage("VPP加载失败");
        //            return false;
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        RunLogMessage("加载程序异常" + ex.ToString());
        //        return false;
        //    }
        //}

        private Boolean BiaodinInit()
        {
            try
            {
                if (File.Exists(外设.SysPras.CalVpppath))
                {
                    外设._相机标定模块 = CogSerializer.LoadObjectFromFile(外设.SysPras.CalVpppath) as CogToolBlock;
                    return true;
                }
                else
                {
                    //加载标定相关参数
                    myLog4.Info("标定文件不存在");
                    外设._相机标定模块 = new CogToolBlock();
                    return false;
                }

            }
            catch (Exception ex)
            {
                myLog4.Info("标定程序加载失败" + ex.Message);
                return false;

            }
        }

        //最后一次的款式

        private Boolean kuanshiInit()
        {


            try
            {
                //

                string[] profiles = Directory.GetFiles(外设.SysPras.Vpppath, "*.yjye");
                filenames.Clear();
                foreach (string file in profiles)
                {
                    filenames.Add(Path.GetFileNameWithoutExtension(file));
                }
                if (filenames.Count == 0)
                {
                    myLog4.Info("未有检测款式，请新建款式");
                    return false;
                }
                cmb_款式选择.Items.Clear();
                this.Invoke((EventHandler)delegate
                {
                    foreach (string file in filenames)
                    {
                        cmb_款式选择.Items.Add(file);
                    }

                });
                myLog4.Info("前次款式名" + 外设.SysPras._前次款式);
                if (!filenames.Contains(外设.SysPras._前次款式))
                {
                    myLog4.Info("前次编号，未找到对应文件加载默认文件");
                    外设.SysPras._前次款式 = filenames[0];
                }
                //判断是否有这个文件
                string path = 外设.SysPras.Vpppath + "\\" + 外设.SysPras._前次款式.Trim() + ".yjye";
                if (!File.Exists(path))
                {
                    myLog4.Info(外设.SysPras._前次款式 + "该编号模型未找到，请确认是否创建");
                    return false;
                }
                ResultFunc result = 外设.jiayumodel.Loadmode(path, out JayuYindaomodel tempmodel);
                if (result.State == Funstate.OK)
                {
                    this.Invoke((EventHandler)delegate
                    {
                        cmb_款式选择.Text = 外设.SysPras._前次款式;
                        txt_当前序号.Text = tempmodel._款式序号.ToString();
                    });
                    外设.jiayumodel.modelone = tempmodel;
                    myLog4.Info(外设.SysPras._前次款式 + "款式切换成功,");
                    return true;
                }
                else
                {
                    myLog4.Info("款式切换失败," + "未能切换到" + 外设.SysPras._前次款式 + "异常" + result.mes);
                    return false;
                }
            }
            catch (Exception ex)
            {
                myLog4.Info(ex.ToString());
                return false;

            }
        }
        //板卡初始化

        private Boolean LightInit()
        {
            Boolean tempresult = true;
            try
            {
                //读取参数
                string path = "光源.xml";
                if (File.Exists(path))
                {
                    外设.LightCtrl.cf = (TGQ_24V50_Config)XmlHelper.LoadXML<TGQ_24V50_Config>(path);
                }
                if (外设.LightCtrl.cf == null)
                {
                    外设.LightCtrl.cf = new TGQ_24V50_Config();
                }

                外设.LightCtrl.Connect();
                if (外设.LightCtrl.Connection)
                {
                    外设.LightCtrl.CloseAll();
                    if (外设.LightCtrl.OpenAll())
                    {
                        myLog4.Info("光源初始化成功");
                    }
                }
                else
                {
                    myLog4.Error("光源初始化失败");
                    tempresult = false;
                }

                return tempresult;

            }
            catch (Exception)
            {

                return false;
            }
        }


        private Boolean HeartInit()
        {
            外设.modbusServer.Connect(502);

            string path = System.AppDomain.CurrentDomain.BaseDirectory + "HeartDebug\\KillAndStartPress.exe";

            if (外设.modbusServer.IsConnect && StartPress(path, "killandstartpress"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion




        #region ============================================工具函数===========================================

        //启动某exe
        public bool StartPress(string name, string startName)
        {
            ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = name;
            info.Arguments = "";
            //指定程序运行状态，最大化、最小化等
            info.WindowStyle = ProcessWindowStyle.Normal;
            //查询软件是否已经启动
            Process[] process = Process.GetProcesses();
            foreach (Process p1 in process)
            {
                try
                {
                    string processName = p1.ProcessName.ToLower().Trim();
                    //判断是否包含阻碍更新的进程
                    if (processName == startName)
                    {
                        return true;
                    }
                }
                catch { }
            }

            Process pro = Process.Start(info);
            //pro.WaitForExit();

            return true;
        }
        private void RunLogMessage(string LogMessage)
        {
            myLog4.Info(LogMessage);
        }

        public void FormDockToPanel(Form fornm, Panel panel)
        {
            panel.Controls.Clear();
            fornm.TopLevel = false;
            fornm.FormBorderStyle = FormBorderStyle.None;
            fornm.Dock = DockStyle.Fill;
            fornm.Parent = panel;
            fornm.Show();
            // xTC_Setting.SelectedTabPageIndex = 0;
        }


        public string SaveimageDisp(string filebisOK, string houzui, Cognex.VisionPro.CogRecordDisplay RecorDis)
        {
            try
            {
                string imagefile = "";
                imagefile = 外设.SysPras.SaveImagepath + "\\" + filebisOK + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";
                if (!File.Exists(imagefile))
                {
                    XmlHelper.CreateDirectoryEx(imagefile);
                }

                string imgName = "";
                imgName = imagefile + "\\" + DateTime.Now.ToString("HHmmssff") + ".jpg";
                Cognex.VisionPro.ImageFile.CogImageFileTool saveima = new Cognex.VisionPro.ImageFile.CogImageFileTool();
                if (RecorDis.Image != null)
                {
                    //saveima.InputImage = RecorDis.
                    saveima.InputImage = RecorDis.Image;
                    saveima.Operator.Open(imgName, CogImageFileModeConstants.Write);
                    saveima.Run();
                    //  RecorDis.cre
                }
                else
                {
                    myLog4.Info("图片保存失败:图片为空");
                }
                return "";
            }
            catch (Exception ex)
            {
                myLog4.Info("图片保存失败:" + ex.Message);
                return ex.Message;
            }
        }

        public string SaveimageDispjietu(string filebisOK, string houzui, Cognex.VisionPro.CogRecordDisplay RecorDis)
        {
            try
            {
                string imagefile = "";
                imagefile = 外设.SysPras.SaveImagepath + "\\" + filebisOK + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";
                if (!File.Exists(imagefile))
                {
                    XmlHelper.CreateDirectoryEx(imagefile);
                }

                string imgName = "";
                imgName = imagefile + "\\" + DateTime.Now.ToString("HHmmssff") + "_" + houzui + ".jpg";
                //   Cognex.VisionPro.ImageFile.CogImageFileTool saveima = new Cognex.VisionPro.ImageFile.CogImageFileTool();
                if (RecorDis.Image != null)
                {
                    //saveima.InputImage = RecorDis.
                    Bitmap saveimagec = RecorDis.CreateContentBitmap(CogDisplayContentBitmapConstants.Image) as Bitmap;
                    saveimagec.Save(imgName, ImageFormat.Jpeg);

                }
                else
                {
                    myLog4.Info("图片保存失败:图片为空");
                }
                return "";
            }
            catch (Exception ex)
            {
                myLog4.Info("图片保存失败:" + ex.Message);
                return ex.Message;
            }
        }
        #endregion





        #region===================================== 主运行函数=======================================

        ushort isPhoto = 0;
        ushort isPhotoOld = 0;
        ResultFunc[] topResult = new ResultFunc[2];
        ResultFunc[] lowResult = new ResultFunc[2];
        bool topDetectOpen = false;
        bool lowDetectOpen = false;

        int topResultOnce = 0;     //0侯机，1是OK，2是NG
        int lowResultOnce = 0;

        private void Autorun()
        {
            //CCD处理判断
            外设.rtuClient.ReadShort(外设.rtuClient.rtuConfig.PhotoCam.ToString(), out isPhoto);

            //上升沿
            if (isPhoto == 1 && isPhotoOld == 0)
            {
                myLog4.Info("相机触发拍照");
                topDetectOpen = true;
                lowDetectOpen = true;               

                Thread.Sleep(200);
                外设.rtuClient.WriteShort(外设.rtuClient.rtuConfig.PhotoCam.ToString(), 0);

            }

            //不等于0时进入判断结果
            if (topResultOnce != 0 && lowResultOnce != 0)
            {
                if (!this.check_Shield.Checked)
                {
                    if (topResultOnce == 1 && lowResultOnce == 1)
                    {
                        外设.rtuClient.WriteShort(外设.rtuClient.rtuConfig.Result.ToString(), 1);
                    }
                    else
                    {
                        外设.rtuClient.WriteShort(外设.rtuClient.rtuConfig.Result.ToString(), 2);
                        Thread.Sleep(PublicValue.sleepTime);
                        外设.rtuClient.WriteShort(外设.rtuClient.rtuConfig.Result.ToString(), 0);
                    }
                }
                else
                {
                    外设.rtuClient.WriteShort(外设.rtuClient.rtuConfig.Result.ToString(), 1);
                }


                topResultOnce = 0;
                lowResultOnce = 0;
            }


            isPhotoOld = isPhoto;
        }

        private void topWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (ExitSta == 1)
            {
                try
                {
                    if (topDetectOpen)
                    {
                        topDetectOpen = false;
                        topResult = CCD_TopDetect();

                        if (topResult[0].State == Funstate.OK && topResult[1].State == Funstate.OK)
                        {
                            topResultOnce = 1;
                            PublicValue.TopOk++;
                        }
                        else
                        {
                            topResultOnce = 2;
                            PublicValue.TopNg++;
                        }

                        
                    }

                }
                catch (Exception ex)
                {

                    RunLogMessage(ex.Message);
                }

                Thread.Sleep(100);
            }
        }

        private void lowWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (ExitSta == 1)
            {
                try
                {
                    if (lowDetectOpen)
                    {
                        lowDetectOpen = false;
                        lowResult = CCD_LowDetect();

                        if (lowResult[0].State == Funstate.OK && lowResult[1].State == Funstate.OK)
                        {
                            lowResultOnce = 1;
                            PublicValue.LowOk++;
                        }
                        else
                        {
                            lowResultOnce= 2;
                            PublicValue.LowNg++;
                        }

                        
                    }

                }
                catch (Exception ex)
                {

                    RunLogMessage(ex.Message);
                }

                Thread.Sleep(100);
            }
        }

        public ResultFunc[] CCD_TopDetect()
        {
            ResultFunc[] resultFunc = 外设.jiayumodel._上工位检测();
            frmDisp_TopCamera1.cogRecordDisplay.Record = 外设.jiayumodel.disprecord1;
            frmDisp_TopCamera1.cogRecordDisplay.Fit();

            frmDisp_TopCamera2.cogRecordDisplay.Record = 外设.jiayumodel.disprecord2;
            frmDisp_TopCamera2.cogRecordDisplay.Fit();
            if (resultFunc[0].State == Funstate.OK)
            {
                //myLog4.Info("上1图片检测OK");
                frmDisp_TopCamera1.lab_OKNG.Text = "OK";
                frmDisp_TopCamera1.lab_OKNG.BackColor = Color.Green;
                if (cbx_图像保存.Checked)
                {
                    SaveimageDisp("OK_上1", "CCD1", frmDisp_TopCamera1.cogRecordDisplay);
                }
            }
            else
            {
                //myLog4.Info("上1图片检测NG");
                frmDisp_TopCamera1.lab_OKNG.Text = "NG";
                frmDisp_TopCamera1.lab_OKNG.BackColor = Color.Red;
                if (cbx_图像保存.Checked || checkB_NGImg.Checked)
                {
                    SaveimageDisp("NG_上1", "img", frmDisp_TopCamera1.cogRecordDisplay);
                    SaveimageDispjietu("NG_上1", "jietu", frmDisp_TopCamera1.cogRecordDisplay);
                }
            }

            if (resultFunc[1].State == Funstate.OK)
            {
                //myLog4.Info("上2图片检测OK");
                frmDisp_TopCamera2.lab_OKNG.Text = "OK";
                frmDisp_TopCamera2.lab_OKNG.BackColor = Color.Green;
                if (cbx_图像保存.Checked)
                {
                    SaveimageDisp("OK_上2", "CCD1", frmDisp_TopCamera2.cogRecordDisplay);
                }
            }
            else
            {
                //myLog4.Info("上2图片检测NG");
                frmDisp_TopCamera2.lab_OKNG.Text = "NG";
                frmDisp_TopCamera2.lab_OKNG.BackColor = Color.Red;
                if (cbx_图像保存.Checked || checkB_NGImg.Checked)
                {
                    SaveimageDisp("NG_上2", "img", frmDisp_TopCamera2.cogRecordDisplay);
                    SaveimageDispjietu("NG_上2", "jietu", frmDisp_TopCamera2.cogRecordDisplay);
                }
            }


            return resultFunc;
        }

        public ResultFunc[] CCD_LowDetect()
        {
            ResultFunc[] resultFunc = 外设.jiayumodel._下工位检测();
            frmDisp_LowCamera1.cogRecordDisplay.Record = 外设.jiayumodel.disprecord3;
            frmDisp_LowCamera1.cogRecordDisplay.Fit();

            frmDisp_LowCamera2.cogRecordDisplay.Record = 外设.jiayumodel.disprecord4;
            frmDisp_LowCamera2.cogRecordDisplay.Fit();
            if (resultFunc[0].State == Funstate.OK)
            {
                //myLog4.Info("下1图片检测OK");
                frmDisp_LowCamera1.lab_OKNG.Text = "OK";
                frmDisp_LowCamera1.lab_OKNG.BackColor = Color.Green;
                if (cbx_图像保存.Checked)
                {
                    SaveimageDisp("OK_下1", "CCD2", frmDisp_LowCamera1.cogRecordDisplay);
                }
            }
            else
            {
                //myLog4.Info("下1图片检测NG");
                frmDisp_LowCamera1.lab_OKNG.Text = "NG";
                frmDisp_LowCamera1.lab_OKNG.BackColor = Color.Red;
                if (cbx_图像保存.Checked || checkB_NGImg.Checked)
                {
                    SaveimageDisp("NG_下1", "img", frmDisp_LowCamera1.cogRecordDisplay);
                    SaveimageDispjietu("NG_下1", "jietu", frmDisp_LowCamera1.cogRecordDisplay);
                }
            }

            if (resultFunc[1].State == Funstate.OK)
            {
                //myLog4.Info("下2图片检测OK");
                frmDisp_LowCamera2.lab_OKNG.Text = "OK";
                frmDisp_LowCamera2.lab_OKNG.BackColor = Color.Green;
                if (cbx_图像保存.Checked)
                {
                    SaveimageDisp("OK_下2", "CCD2", frmDisp_LowCamera2.cogRecordDisplay);
                }
            }
            else
            {
                //myLog4.Info("下2图片检测NG");
                frmDisp_LowCamera2.lab_OKNG.Text = "NG";
                frmDisp_LowCamera2.lab_OKNG.BackColor = Color.Red;
                if (cbx_图像保存.Checked || checkB_NGImg.Checked)
                {
                    SaveimageDisp("NG_下2", "img", frmDisp_LowCamera2.cogRecordDisplay);
                    SaveimageDispjietu("NG_下2", "jietu", frmDisp_LowCamera2.cogRecordDisplay);
                }
            }


            return resultFunc;

        }



        short isManualPhoto = 0;
        private void ManulRun()
        {
            
        }
        private void ErrStatus()
        {

        }


        #endregion

        #region =============================================主页按键功能===========================================

        private void btn_视觉流程_Click(object sender, EventArgs e)
        {
            外设.jiayumodel.setconfig();
        }

        private void btn_PLC配置_Click(object sender, EventArgs e)
        {
            外设.rtuClient.setConfig();
        }

        private void btn_光源控制_Click(object sender, EventArgs e)
        {
            Frm_光源控制 tempF = new Frm_光源控制(外设.LightCtrl);
            tempF.Show();
        }

        private void btn_系统设置_Click(object sender, EventArgs e)
        {
            SysTemDataFrm tempF = new SysTemDataFrm();
            tempF.Show();
        }

        private void btn_权限登录_Click(object sender, EventArgs e)
        {
            Frm_Login tempF = new Frm_Login();
            tempF.Show();
        }


        #endregion



        #region =============================================工具按键功能===========================================
        private void btn_键盘_Click(object sender, EventArgs e)
        {
            string path = @"C:\windows\system32\osk.exe";
            if (System.IO.File.Exists(path))
            {
                System.Diagnostics.Process.Start(path);
            }
            else
            {

            }
        }

        private void btn_计算器_Click(object sender, EventArgs e)
        {
            string path = @"C:\Windows\System32\calc.exe";
            if (System.IO.File.Exists(path))
            {
                System.Diagnostics.Process.Start(path);
            }
            else
            {

            }
        }

        private void btn_截图_Click(object sender, EventArgs e)
        {
            string path = @"C:\Windows\system32\SnippingTool.exe";
            if (System.IO.File.Exists(path))
            {
                System.Diagnostics.Process.Start(path);
            }
            else
            {

            }
        }

        private void btn_打开图片_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(外设.SysPras.SaveImagepath);
        }

        private void btn_打开日志_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(外设.SysPras.Logpath);
        }



        #endregion




        #region =========================================手动操作==========================================

        private void btn_采集图片_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    外设.jiayumodel.modelone._BFifoAcq_tool.Run();
            //    cogRecordDisplay1.Record = 外设.jiayumodel.modelone._BFifoAcq_tool.CreateLastRunRecord().SubRecords[0];
            //    cogRecordDisplay1.Fit();

            //}
            //catch (Exception EX)
            //{

            //    System.Windows.Forms.MessageBox.Show("打开实时失败" + EX.Message);
            //}
        }

        private void btn_手动自动_Click(object sender, EventArgs e)
        {
            if (Appstates == 1)
            {
                Appstates = 0;
            }
            else
            {
                Appstates = 1;
            }
        }


        private void btn_TopTest1_Click(object sender, EventArgs e)
        {
            if (Appstates != 1)
            {
                Stopwatch sw1 = new Stopwatch();
                sw1.Start();
                CCD_TopDetect();
                sw1.Stop();
                myLog4.Info("耗时" + sw1.ElapsedMilliseconds.ToString());

            }
            else
            {
                MessageBox.Show("当前在自动中，请切回手动");
                myLog4.Info("当前在自动中，请切回手动");
            }
        }



        private void btn_LowTest1_Click(object sender, EventArgs e)
        {
            if (Appstates != 1)
            {
                Stopwatch sw1 = new Stopwatch();
                sw1.Start();
                CCD_LowDetect();
                sw1.Stop();
                myLog4.Info("耗时" + sw1.ElapsedMilliseconds.ToString());

            }
            else
            {
                MessageBox.Show("当前在自动中，请切回手动");
                myLog4.Info("当前在自动中，请切回手动");
            }
        }





        private void btn_查看图片_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(外设.SysPras.SaveImagepath);
        }

        #endregion




        




        private void main_thread_DoWork(object sender, DoWorkEventArgs e)
        {
            while (ExitSta == 1)
            {
                try
                {
                    switch (Appstates)
                    {
                        case 0:
                            ManulRun();
                            break;
                        case 1:
                            Autorun();
                            break;
                        case 2:
                            ErrStatus();
                            break;
                        default:
                            break;

                    }

                }
                catch (Exception ex)
                {

                    RunLogMessage(ex.Message);
                }

                Thread.Sleep(100);
            }
        }


        short heart = 0;
        private void DoOtherWork_DoWork(object sender, DoWorkEventArgs e)
        {
            while (ExitSta == 1)
            {
                try
                {
                    heart++;
                    外设.modbusServer.WriteShort("1000", heart);
                    if (heart > 10000)
                    {
                        heart = 0;
                    }

                    //自动删除超出间隔时间的文件
                    PublicFuntions.DeleateFile(外设.SysPras.SaveImagepath, 外设.SysPras._间隔天);  //OK路径下的图片
                    PublicFuntions.DeleateFile(外设.SysPras.SaveImagepath, 外设.SysPras._间隔天);  //NG路径下的图片

                    //if (PublicValue.ProductRecord)          //如果选中保存文档，则定期删除生产文档数据                                                                                                                                 //{ PublicFuntions.DeleateFile(PublicValue.ProductRecordPath, PublicValue.ProductRecordDel); }
                    PublicFuntions.WriteINI("生产数据", "TopOk", PublicValue.TopOk.ToString(), PublicValue.SystemIniPath);
                    PublicFuntions.WriteINI("生产数据", "TopNg", PublicValue.TopNg.ToString(), PublicValue.SystemIniPath);
                    PublicFuntions.WriteINI("生产数据", "LowOk", PublicValue.LowOk.ToString(), PublicValue.SystemIniPath);
                    PublicFuntions.WriteINI("生产数据", "LowNg", PublicValue.LowNg.ToString(), PublicValue.SystemIniPath);
                    PublicFuntions.WriteINI("生产数据", "SleepTime", PublicValue.sleepTime.ToString(), PublicValue.SystemIniPath);
                    PublicFuntions.WriteINI("生产数据", "datetime", DateTime.Now.ToString(), PublicValue.SystemIniPath);
                    //计数清零
                    if (DateTime.Now.Month != PublicValue._chanliangdata.Month || DateTime.Now.Day != PublicValue._chanliangdata.Day)
                    {

                        PublicValue._chanliangdata = DateTime.Now;
                        PublicValue.TopOk = 0;
                        PublicValue.TopNg = 0;
                        PublicValue.LowOk = 0;
                        PublicValue.LowNg = 0;
                    }
                }
                catch (Exception ex)
                {
                    myLog4.Error(ex.ToString());
                }
                Thread.Sleep(10000);
            }
        }

        private void 显示_tick_Tick(object sender, EventArgs e)
        {
            this.Invoke((EventHandler)delegate
            {
                if (Appstates == 0)
                {
                    btn_手动自动.Text = "手动中";
                    btn_手动自动.BackColor = Color.Yellow;
                    btn_TopTest1.Enabled = true;
                    // btn_realdisplay.Enabled = true;
                }
                else if (Appstates == 1)
                {
                    btn_手动自动.Text = "自动中";
                    btn_手动自动.BackColor = Color.Green;
                    btn_TopTest1.Enabled = true;
                    //btn_realdisplay.Enabled = false;
                }

                //更新显示
                this.lab_利用率.Text = PublicFuntions.GetSoftWareARM();
                //C盘容量
                string CtotalV = PublicFuntions.GetHardDiskSpace("C").ToString();
                string CremainV = PublicFuntions.GetHardDiskFreeSpace("C").ToString();
                this.lab_C盘容量.Text = CremainV + "/" + CtotalV;


                //权限
                if (PublicValue.LoginRight == 1)
                {
                    lab_用户权限.Text = "操作员";
                }
                else if (PublicValue.LoginRight == 2)
                {
                    lab_用户权限.Text = "技术员";
                }
                else if (PublicValue.LoginRight == 3)
                {
                    lab_用户权限.Text = "管理员";
                }

                lab_TopOk.Text = PublicValue.TopOk.ToString();
                lab_TopNg.Text = PublicValue.TopNg.ToString();
                lab_TopSum.Text = (PublicValue.TopOk + PublicValue.TopNg).ToString();
                lab_LowOk.Text = PublicValue.LowOk.ToString();
                lab_LowNg.Text = PublicValue.LowNg.ToString();
                lab_LowSum.Text = (PublicValue.LowOk + PublicValue.LowNg).ToString();

            });


        }

        private void time_PLC刷新_Tick(object sender, EventArgs e)
        {


        }



        #region ================================================数据和日志==================================
        private void btn_清除_Click(object sender, EventArgs e)
        {
            PublicValue.TopOk = 0;
            PublicValue.TopNg = 0;
            PublicValue.LowOk = 0;
            PublicValue.LowNg = 0;
        }

        private void btn_更多日志_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(外设.SysPras.Logpath);
        }
        #endregion





        #region ============================================款式切换=============================================

        List<string> filenames = new List<string>();

        private void btn_款式搜索_Click(object sender, EventArgs e)
        {
            string[] profiles = Directory.GetFiles(外设.SysPras.Vpppath, "*.yjye");
            filenames.Clear();
            foreach (string file in profiles)
            {
                filenames.Add(Path.GetFileNameWithoutExtension(file));
            }
            if (filenames.Count == 0)
            {
                myLog4.Info("未检测到款式，请新建款式");
                return;
            }
            cmb_款式选择.Items.Clear();
            this.Invoke((EventHandler)delegate
            {
                foreach (string file in filenames)
                {
                    cmb_款式选择.Items.Add(file);
                }

            });

            cmb_款式选择.Text = 外设.jiayumodel.modelone._款式名称;
        }

        private void btn_款式切换_Click(object sender, EventArgs e)
        {
            //根据当前名字加载款式，并初始化      
            string path = 外设.SysPras.Vpppath + "\\" + cmb_款式选择.Text.ToString() + ".yjye";
            if (!File.Exists(path))
            {
                myLog4.Info("该编号模型未找到，请确认是否创建");
                return;
            }
            ResultFunc result = 外设.jiayumodel.Loadmode(path, out JayuYindaomodel tempmodel);
            if (result.State == Funstate.OK)
            {
                //原模型编号，序号
                int xuhao = 外设.jiayumodel.modelone._款式序号;
                string bianhao = 外设.jiayumodel.modelone._款式名称;
                外设.jiayumodel.modelone = tempmodel;
                txt_当前序号.Text = tempmodel._款式序号.ToString();
                myLog4.Info("款式切换成功," + "由原款式序号：" + xuhao + "编号:" + bianhao + "切换到：款式序号" + tempmodel._款式序号 + "名称：" + tempmodel._款式名称);
            }
            else
            {
                myLog4.Info("款式切换失败," + "未能切换到" + cmb_款式选择.ToString() + "异常" + result.mes);
            }
            外设.SysPras._前次款式 = 外设.jiayumodel.modelone._款式名称;
            if (XmlHelper.SaveXML(SystemPras.SyspPrasFpath, 外设.SysPras) == "")
            {
                myLog4.Info("保存成功");
            }
            else
            {
                myLog4.Info("保存失败");
            }
        }

        #endregion






        #region =============================================帮助按键功能===========================================
        private void btn_帮助_Click(object sender, EventArgs e)
        {

        }

        private void btn_关于_Click(object sender, EventArgs e)
        {

        }



        #endregion

        

        private void numUD_SleepTime_ValueChanged(object sender, EventArgs e)
        {
            PublicValue.sleepTime = int.Parse(this.numUD_SleepTime.Text);
        }

        private void button_ClearCam_Click(object sender, EventArgs e)
        {
            外设.rtuClient.WriteShort(外设.rtuClient.rtuConfig.PhotoCam.ToString(), 0);
        }
    }
}
